//index.js
//获取应用实例
const app = getApp()
const util = require('../../utils/util.js')
const citys = require('../../utils/city.js')
var context = {}
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js')
var qqmapsdk;

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    statubar_height: 0,
    isshowAD: false,
    showProfile: 'none',
    currentPage: 1,
    videoIndex: 0,
    videoList: [],
    liked: false,
    liked_img: '../img/favorite.png',
    showMsg: 'block',
    recommondData: [],
    copy_status: {
      wx_copied: false,
      dy_copied: false,
      wb_copied: false,
      qq_copied: false,
    },
    contacts: {
      wechatNo: '',
      weiboNo: '',
      douyinNo: '',
      qqNo: '',
    },
    _currentPage: 0,
    test: 'block',
    showPlayer: 'block',
    region: [Object.keys(citys), citys[Object.keys(citys)[0]]],
    select: ["", ""],
    city: '',
    cityList: [],
    citylastIndex: -1,
    isplay: true,
    // 触摸开始时间
    touchStartTime: 0,
    // 触摸结束时间
    touchEndTime: 0,
    // 最后一次单击事件点击发生时间
    lastTapTime: 0,
    playVoice: true,
    c_currentPage: 1,
    loadding: 'block',
  },

  test: function(e) {
    if (this.data._currentPage != 0) {
      this.setData({
        test: 'none'
      })
    }
  },

  test1: function(e) {
    if (this.data._currentPage == 0) {
      this.setData({
        test: 'block'
      })
    }
  },

  showPlayer: function(e) {
    this.setData({
      showPlayer: 'block'
    })
  },

  hidePlayer: function(e) {
    this.setData({
      showPlayer: 'none'
    })
  },

  bindColumnChange: function(e) {

    if (e.detail.column === 0) {
      var region = this.data.region;
      var province = region[0][e.detail.value];
      console.log(region[0])
      this.setData({
        region: [region[0], citys[province]]
      });
    }
  },

  bindChange: function(e) {
    if (!e.detail.value || e.detail.value.length < 2) return;
    var region = this.data.region;
    var pro_index = e.detail.value[0];
    var city_index = e.detail.value[1];
    this.setData({
      city: region[1][city_index],
      c_currentPage: 1,
    })

    this.data.cityList = []

    this.getCityList()
  },

  onLoad: function() {

    context = wx.createVideoContext('indexVideo', this)
    //地图组件初始化
    qqmapsdk = new QQMapWX({
      key: 'WTWBZ-LI7LU-XPVVU-2PQ7Y-FLOL5-RQFQI'
    })

    wx.getSetting({
      success: function(res) {
        console.log('debug' + res.authSetting['scope.userInfo'])
        if (!res.authSetting['scope.userInfo']) {
          wx.redirectTo({
            url: '../login/login',
          })
        }
        return
      }
    })

    this.getPosition()
    console.log('videoList')
      console.log(this.data)
      console.log(this.data.videoList)
      console.log(this.data.userInfo)
    if (this.data.videoList.length <= 0) {
      this.setData({
        playVoice: false,
      })
      wx.navigateTo({
        url: '../splash/splash',
      })
      console.log('still work')
    }

    this.setData({
      statubar_height: app.globalData.statubar_height
    })

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,

      })
      this.getVideoList()
      // this.getRecommond()
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        this.getVideoList()
        // this.getRecommond()
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }

  },

  //获取用户位置信息
  getPosition: function() {
    var that = this
    wx.getLocation({
      success: function(res) {
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },

          success: function(addressRes) {
            var address = addressRes.result.address_component.city;

            that.setData({
              city: address
            })
          },

          complete: function(res) {

          }
        })
      },
    })
  },

  disMove: function(e) {

  },

  // 我的收藏
  favorite: function(e) {
    wx.navigateTo({
      url: '../my-favorite/my-favorite',
    })
  },

  //我要反馈
  suggest: function(e) {
    wx.navigateTo({
      url: '../suggest/suggest',
    })
  },

  //应用盒子
  box: function(e) {
    wx.navigateTo({
      url: '../box/box',
    })
  },

  //tabbar切换页面
  switchTab: function(e) {
      console.log('tabbar')
      console.log(e)
    if (this.data._currentPage == e.currentTarget.dataset.currentpage) {

      return
    }

    if (e.currentTarget.dataset.currentpage != 0) {
      context.pause()
    } else {
      context.play()
    }

    let navigateUrl = ''
    switch (e.currentTarget.dataset.currentpage) {
      case '0':
        this.setData({
          _currentPage: 0,
        })
        context.play()
        break
      case '1':
        this.setData({
          _currentPage: 1,
        })
        break
      case '2':
        this.setData({
          _currentPage: 2,
        })

        this.getCityList()
        break
      case '3':
        wx.navigateTo({
          url: '../add/add',
        })

        break
    }
  },

  //添加收藏
  addFav: function(e) {
    var isFav = e.currentTarget.dataset.isfav
    var that = this
    var param = {
      userNo: app.globalData.userInfo.userNo,
      douyinUid: e.currentTarget.dataset.dyno
    }

    if (isFav == '1') {
      util.request('/douyin/cancelCollectUser', param, function(res) {
        that.data.videoList[that.data.videoIndex]['isCollect'] = 0
        that.setData({
          videoList: that.data.videoList
        })
      })
    } else {
      util.request('/douyin/collectUser', param, function(res) {
        that.data.videoList[that.data.videoIndex]['isCollect'] = 1
        that.setData({
          videoList: that.data.videoList
        })
      })
    }

  },

  //记录用户是否已读
  recordIsRead: function() {
    let item = this.data.videoList[this.data.videoIndex]
    let param = {
      "douYinUserNo": item.douyinUserNo,
      "index": item.index,
      "userNo": app.globalData.userInfo.userNo
    }
    util.request('/douyin/recordUserRead', param, function(res) {
      console.log(res)
    })
  },

  //推荐跳转
  play: function(e) {
    let dyUserNo = e.currentTarget.dataset.userno

    wx.navigateTo({
      url: '../player/player?userNo=' + dyUserNo,
    })
  },

  //获取推荐内容
  getRecommond: function(callback) {
    var that = this
    util.request('/douyin/queryRecommendList', {
      userNo: app.globalData.userInfo.userNo,
      currentPage: this.data.currentPage,
      pageSize: '10'
    }, function(res) {
      console.log(res)
      that.setData({

        recommondData: res
      })
      callback(res)
    })
  },

  //点赞
  like: function(e) {
    let videoList = this.data.videoList
    let index = this.data.videoIndex

    if (videoList[index].isClickGood == '0') {
      videoList[index].isClickGood = '1'
      videoList[index].charmCount += 1
    } else if (videoList[index].isClickGood == '1') {
      videoList[index].isClickGood = '0'
      videoList[index].charmCount -= 1
    }

    this.setData({
      videoList: videoList,
    })

    util.request('/douyin/userClickGood', {
      userNo: app.globalData.userInfo.userNo,
      douyinUserNo: videoList[index].douyinUserNo
    }, function(res) {
      console.log(res)
    })
  },


  //获取视频列表
  getVideoList: function(act) {

console.log('still get video')
    let that = this
    let currentPage = this.data.currentPage
    let videoIndex = this.data.videoIndex
    if (act == 'last') {
      if (currentPage <= 1) {
        if (this.data.videoIndex == 0) {
          this.showPlayer()
        }
        wx.showToast({
          title: '当前已是第一页',
        })

        return
      }
      currentPage = this.data.currentPage - 1
      videoIndex = 9
    } else if (act == 'next') {
      currentPage = this.data.currentPage + 1
      videoIndex = 0
    }
    let params = {
      // currentPage: currentPage,
      pageSize: 10,
      userNo: app.globalData.userInfo.userNo,
    }

    console.log(app.globalData.userInfo.userNo)
    util.request('/douyin/queryVideoList', params, function(res1) {
      console.log(res1)
      that.setData({
        videoList: res1,
        videoIndex: videoIndex,
        currentPage: currentPage,
      })

      if (currentPage <= 1) {
        if (that.data.videoIndex == 0) {
          that.recordIsRead()
        }
      }

      if (that.data.recommondData[0]) {
        return
      } else {
        that.getRecommond(function() {
          //
        })
      }

      // wx.hideLoading()
    })
  },

  //请求同城列表
  getCityList: function() {
    var that = this

    var city = {
      cityName: this.data.city,
      userNo: this.data.userInfo.userNo,
      currentPage: this.data.c_currentPage,
      pageSize: 10,
    }
    console.log(city)
    util.request('/douyin/queryCityVideoList', city, function(res) {
      console.log(res)
      that.setData({
        cityList: res ? that.data.cityList.concat(res) : that.data.cityList,
        loadding: 'none',
      })
    })
  },

  //视频点击播放暂停
  isplay: function(e) {

  },

  //双击下一条视频
  /// 按钮触摸开始触发的事件
  touchStart: function(e) {
    this.touchStartTime = e.timeStamp
  },

  /// 按钮触摸结束触发的事件
  touchEnd: function(e) {
    this.touchEndTime = e.timeStamp
  },

  doubleClick: function(e) {
    var that = this
    // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
    if (that.touchEndTime - that.touchStartTime < 350) {
      // 当前点击的时间
      var currentTime = e.timeStamp
      var lastTapTime = that.lastTapTime
      // 更新最后一次点击时间
      that.lastTapTime = currentTime

      // 如果两次点击时间在300毫秒内，则认为是双击事件
      if (currentTime - lastTapTime < 300) {
        that.swicthVideo({
          currentTarget: {
            dataset: {
              act: 'next'
            }
          }
        })
      }
    }
  },
  //跳转个人主页
  showPro: function(e) {
    wx.navigateTo({
      url: '../profile/profile?data=' + JSON.stringify({
        'douyinUid': e.currentTarget.dataset.douyinno,
        'userNo': this.data.userInfo.userNo
      }),
    })
  },

  //视频切换
  swicthVideo: function(e) {
    if (!util.clickable()) {
      return
    }
    this.hidePlayer()

    this.isUnlock()
    let copy_statu = {
      wx_copied: false,
      dy_copied: false,
      wb_copied: false,
      qq_copied: false,
    }
    let contacts = {
      wechatNo: '',
      weiboNo: '',
      douyinNo: '',
      qqNo: '',
    }

    this.setData({
      copy_status: copy_statu,
      contacts: contacts
    })
    let act = e.currentTarget.dataset.act
    let that = this
    let videoIndex = this.data.videoIndex

    if (act == 'last') {
      if (videoIndex <= 0) {
        that.getVideoList('last')
      } else {
        this.setData({
          videoIndex: videoIndex - 1
        })
      }

    } else if (act == 'next') {
      console.log(this.data.videoList.length)
      if (videoIndex >= this.data.videoList.length - 1) {
        that.getVideoList('next')
      } else {
        this.setData({
          videoIndex: videoIndex + 1
        })
      }
      this.recordIsRead()
    }

    this.setData({
      liked: this.data.videoList[this.data.videoIndex].liked ? true : false
    })
  },

  //视频是否需要解锁
  isUnlock: function() {
    let param = {
      "userNo": this.data.userInfo.userNo,
      "wxOpenId": app.globalData.userInfo.openId,
    }
    util.request('/douyin/isNeedUnLock', param, function(res) {
      console.log(res)
    })
  },

  //复制联系方式
  copy: function(e) {
      console.log()
    let data = e.currentTarget.dataset.contact
    let type = e.currentTarget.dataset.type         //"dy_copied"
    let notype = e.currentTarget.dataset.notype  // "douyinNo"
    let douyinNo = e.currentTarget.dataset.douyinno
    let index = this.data._currentPage == 0 ? this.data.videoIndex : e.currentTarget.dataset.index
    let lastIndex = this.data.cityLastIndex
    let list = this.data._currentPage == 0 ? this.data.videoList : this.data.cityList
    // let 
    let that = this
    let copy_statu = {
      wx_copied: false,
      dy_copied: false,
      wb_copied: false,
      qq_copied: false,
    }
    
    list[index]['contacts'] = this.data.contacts
    if (that.data._currentPage != 0 && lastIndex >= 0) {
      list[index]['contacts'] = {}
    }


    if (list[index]['contacts'][notype]) {

      if (that.data._currentPage != 0 && lastIndex >= 0) {
        list[lastIndex]['copy_status'] = {}
      }

      wx.setClipboardData({
        data: data,
        success: function(res) {
          copy_statu[type] = true

          if (that.data._currentPage != 0 && index >= 0) {
            list[index]['copy_status'] = copy_statu

          }
          that.setData({
            copy_status: that.data._currentPage != 0 && index >= 0 ? {} : copy_statu,
            cityList: list,
            cityLastIndex: that.data._currentPage != 0 && index >= 0 >= 0 ? index : -1,
          })
        }
      })
    } else {
      let param = {
        "douyinUserNo": douyinNo,
        "type": type.substring(0, 2)
      }
      console.log(param)
      util.request('/douyin/getSocialContactInfo', param, function(res) {
        list[index]['contacts'][notype] = res
        if (that.data._currentPage == 0) {
          that.setData({
            videoList: list
          })
        } else {
          that.setData({
            cityList: list
          })
        }

      })

      if (that.data._currentPage != 0 && lastIndex >= 0) {
        list[lastIndex]['copy_status'] = {}
      }

      wx.setClipboardData({
        data: data,
        success: function(res) {
          copy_statu[type] = true

          if (that.data._currentPage != 0 && index >= 0) {
            list[index]['copy_status'] = copy_statu

          }
          that.setData({
            copy_status: index >= 0 ? {} : copy_statu,
            cityList: list,
            cityLastIndex: index >= 0 ? index : -1,
          })
        }
      })
    }
  },

  // 展示广告
  showAD: function(e) {
    var that = this
    if (this.data.recommondData[0]) {
      that.setData({
        isshowAD: !that.data.isshowAD,
        showMsg: that.data.isshowAD ? 'block' : 'none',
      })
    } else {
      this.getRecommond(function(res) {
        that.setData({
          isshowAD: !that.data.isshowAD,
          showMsg: that.data.isshowAD ? 'block' : 'none',
        })
      })
    }

  },

  onShow: function() {
    // this.getRecommond()
    // context.play()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  c_loadMore: function(e) {
    this.setData({
      c_currentPage: this.data.c_currentPage + 1,
      loadding: 'block',
    })
    this.getCityList()
  },

  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }

})